package com.example.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * @author zhangs
 * @version v1.0
 * @decription jdbc工具类
 * @date 2021/4/3 12:42
 **/
public class JdbcUtils {
    private static Properties props = null;
    // 每个线程都有一个独有的连接
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    /**
     * 从配置文件中获取数据库配置
     *
     * @param path 文件路径
     * @return
     * @throws IOException
     */
    private static Properties getProperties(String path) throws IOException {
        // 获取线程类加载器
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        // 使用线程类加载输入流
        InputStream is = cl.getResourceAsStream(path);
        // 创建Properties
        Properties properties = new Properties();
        properties.load(is);
        return properties;
    }

    /**
     * 获取数据库连接
     *
     * @param path
     * @return
     */
    public static Connection getConnection(String path) throws Exception {
        Connection conn = tl.get();
        if (conn == null) {
            if (props == null) {
                // 1.获取属性
                props = getProperties(path);
                // 2.加载相应的数据库驱动
                Class.forName(props.getProperty("jdbc.driver"));
            }

            // 3.获取数据库连接
            String url = props.getProperty("jdbc.url");
            String username = props.getProperty("jdbc.username");
            String password = props.getProperty("jdbc.password");
            conn = DriverManager.getConnection(url, username, password);
            tl.set(conn);
        }
        return conn;
    }

    /**
     * 关闭相关的连接
     *
     * @param closeable
     */
    public static void close(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
